<template>
  <div>
    <van-field
      v-model="resultLabel"
      v-bind="$attrs"
      readonly
      is-link
      @click="show = !show"
    />
    <van-popup v-model="show" position="bottom">
      <van-picker
        :columns="columns"
        show-toolbar
        :value-key="this.option.label"
        :title="$attrs.label"
        @cancel="show = !show"
        @confirm="onConfirm"
        @change="change"
      />
    </van-popup>
  </div>
</template>

<script>
import { Picker } from 'vant'
export default {
  name: 'VanFieldSelectPicker',
  components: {
    vanPicker: Picker,
  },
  model: {
    prop: "selectValue"
  },
  props: {
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    selectValue: {
      type: [String, Number],
      default: ''
    },
    option: {
      type: Object,
      default: function () {
        return { label: 'Name', value: 'ID' }
      }
    }
  },
  computed: {
    resultLabel: {//双向绑定的数据做修改需要用get/set
      get () {
        const res = this.columns.filter(item => {
          return item[this.option.value] === this.resultValue
        })
        return res.length ? res[0][this.option.label] : ''
      },
      set () {

      }
    }
  },
  data() {
    return {
      show: false,
      resultValue: this.selectValue
    };
  },
  methods: {
    onConfirm(value, index) {
      this.resultValue = value[this.option.value]
      this.show = !this.show;
      this.$emit('getMessage', value, index, this.resultValue)
      //this.$emit("getMessage", v.ID,v.Name);//把value值传给父组件
    },
    change (val, index) {//当数据改变
      this.$emit('change', val, index, this.resultValue)
    },
    cancel (val, index) {//取消
      this.show = !this.show
      this.$emit('cancel', val, index, this.resultValue)
    }
  },
  watch: {
    selectValue: function (newVal) {//监听变化初始赋值
      this.resultValue = newVal
    },
    resultValue (val) {//当所选数据变化，组件model的双向绑定
      this.$emit('input', val)
    }
  }
};
</script>

<style></style>